from PIL import Image
import os

target_size = (128, 128)
target_format = "JPEG"
input_folder = "C:/Users/Administrator/Desktop/异宠APP相关/图片处理/input"
output_folder = "C:/Users/Administrator/Desktop/异宠APP相关/图片处理/output"

def convert_image(img):
    """处理图像模式兼容性"""
    if img.mode in ('RGBA', 'LA'):
        # 创建白色背景并合并Alpha通道
        background = Image.new('RGB', img.size, (255, 255, 255))
        background.paste(img, mask=img.split()[-1])  # 使用Alpha通道作为蒙版
        return background
    elif img.mode == 'P':
        # 处理调色板模式图像
        return img.convert('RGB')
    else:
        return img.convert('RGB')

def center_crop(img, target_size):
    """中心裁剪图片为目标比例"""
    target_ratio = target_size[0] / target_size[1]
    img_ratio = img.width / img.height
    if img_ratio > target_ratio:
        # 图片太宽，裁掉两侧
        new_width = int(img.height * target_ratio)
        left = (img.width - new_width) // 2
        right = left + new_width
        top = 0
        bottom = img.height
    else:
        # 图片太高，裁掉上下
        new_height = int(img.width / target_ratio)
        top = (img.height - new_height) // 2
        bottom = top + new_height
        left = 0
        right = img.width
    return img.crop((left, top, right, bottom))

for root, dirs, files in os.walk(input_folder):
    for filename in files:
        if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.webp')):
            input_path = os.path.join(root, filename)
            relative_path = os.path.relpath(root, input_folder)
            output_dir = os.path.join(output_folder, relative_path)
            
            os.makedirs(output_dir, exist_ok=True)
            
            try:
                with Image.open(input_path) as img:
                    # 转换图像模式
                    img = convert_image(img)
                    # 先中心裁剪为目标比例
                    img_cropped = center_crop(img, target_size)
                    # 再缩放到目标尺寸
                    img_resized = img_cropped.resize(target_size, Image.Resampling.LANCZOS)
                    output_path = os.path.join(output_dir, f"{os.path.splitext(filename)[0]}.{target_format.lower()}")
                    
                    # 添加JPEG保存参数
                    img_resized.save(
                        output_path, 
                        format=target_format,
                        quality=85,       # 添加质量参数
                        optimize=True,     # 启用优化
                        subsampling=0      # 保持色度采样
                    )
                    print(f"成功处理: {input_path} -> {output_path}")
                    
            except Exception as e:
                print(f"处理失败 {input_path}: {str(e)}")
